//
//  DeviceDataInfoViewController.m
//  sentorise
//
//  Created by admin on 2025/8/28.
//

#import "DeviceDataInfoViewController.h"
#import "GlobalDefine.h"
#import "BTManager.h"
#import "ProgressHUD.h"
#import "DeviceMoreInfoViewController.h"
#import "DeviceCellViewController.h"
#import "DeviceBMSViewController.h"
#import "DeviceDCViewController.h"
#import "PlayManager.h"

@interface DeviceDataInfoViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UILabel *stateLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIView *socView1;
@property (weak, nonatomic) IBOutlet UIView *socView2;
@property (weak, nonatomic) IBOutlet UIView *socView3;
@property (weak, nonatomic) IBOutlet UIView *socView4;
@property (weak, nonatomic) IBOutlet UIView *socView5;
@property (weak, nonatomic) IBOutlet UIView *socView6;
@property (weak, nonatomic) IBOutlet UIView *socView7;
@property (weak, nonatomic) IBOutlet UIView *socView8;
@property (weak, nonatomic) IBOutlet UIView *socView9;
@property (weak, nonatomic) IBOutlet UIView *socView10;
@property (weak, nonatomic) IBOutlet UILabel *scoLabel;

@property (weak, nonatomic) IBOutlet UIImageView *tempIV;
@property (weak, nonatomic) IBOutlet UILabel *tempCLabel;
@property (weak, nonatomic) IBOutlet UILabel *tempFLabel;
@property (weak, nonatomic) IBOutlet UILabel *capacityLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentLabel;
@property (weak, nonatomic) IBOutlet UILabel *voltageLabel;

@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
@property (weak, nonatomic) IBOutlet UIImageView *balanceIV;
@property (weak, nonatomic) IBOutlet UILabel *cellLabel;
@property (weak, nonatomic) IBOutlet UIImageView *cellIV;
@property (weak, nonatomic) IBOutlet UILabel *bmsLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bmsIV;

@property (weak, nonatomic) IBOutlet UIButton *swBtn;
@property (weak, nonatomic) IBOutlet UIView *tipsView;
@property (weak, nonatomic) IBOutlet UILabel *tipsLabel;

@property (weak, nonatomic) IBOutlet UILabel *capTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *curTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *voltTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *bleTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *moreTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *controlTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipsContentLabel;

@property (nonatomic, assign) CGFloat    current;
@property (nonatomic, assign) CGFloat    voltage;
@property (nonatomic, assign) CGFloat    capacity;
@property (nonatomic, assign) CGFloat    fullCapicity;  //满电电容
@property (nonatomic, assign) CGFloat  templerature;  //温度

@property (nonatomic, assign) NSInteger voltageSingleExceed;            //单节过压
@property (nonatomic, assign) NSInteger voltageSingleLower;             //单节欠压
@property (nonatomic, assign) NSInteger voltageTotalLower;              //总压欠压
@property (nonatomic, assign) NSInteger chargingExceed;                 //充电过流
@property (nonatomic, assign) NSInteger disChargingExceed;              //放电过流
@property (nonatomic, assign) NSInteger disChargingTemperatureExceed;   //放电过温
@property (nonatomic, assign) NSInteger chargingTemperatureLower;       //充电低温
@property (nonatomic, assign) NSInteger disChargingTemperatureLower;    //放电低温
@property (nonatomic, assign) NSInteger voltageDifferenceExceed;        //压差过大

@property (nonatomic, assign) NSInteger preMOS;     //预充MOS管
@property (nonatomic, assign) NSInteger chgMOS;     //充电MOS管
@property (nonatomic, assign) NSInteger dsgMOS;     //放电MOS管
@property (nonatomic, assign) NSInteger preRelay;   //预充继电器
@property (nonatomic, assign) NSInteger chgRelay;   //分口充电继电器
@property (nonatomic, assign) NSInteger dsgRelay;   //分口放电继电器
@property (nonatomic, assign) NSInteger mainRelay;  //同口主继电器

@property (nonatomic, strong) NSMutableArray *alarmRealtimeDataList;
@property (nonatomic, assign) NSInteger queryOrder;     //查询指令
@property (nonatomic, assign) BOOL isCurrentPage;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, assign) NSInteger cycles;
@property (nonatomic, assign) NSInteger haveBalance;

@end

@implementation DeviceDataInfoViewController
{
    NSInteger heatTag;
    NSInteger afe1;
    NSInteger afe2;
    NSInteger eepCommunicate;
    NSInteger cbcCHG;
    NSInteger can;
    NSInteger spi;
    NSInteger Upper;
    NSInteger Client1;
    NSInteger LCD;
    NSInteger Wifi;
    NSInteger BLE;
    NSInteger APP;
    NSInteger EEPstorage;
    NSInteger HSE;
    NSInteger LSE;
    NSInteger FLASH;
    NSInteger BALANCE;
    NSInteger ADC;
    NSInteger HEAT;
    NSInteger COOL;
    NSInteger res5;
    NSInteger res6;
    NSInteger Vcell_0v;
    NSInteger Vcell_UV;
    NSInteger Vbat_0V;
    NSInteger Vbat_UV;
    NSInteger CHG_0C;
    NSInteger DSG_0C;
    NSInteger Cellchg_0T;
    NSInteger Celldsg_0T;
    NSInteger Cellchg_UT;
    NSInteger Celldsg_UT;
    NSInteger Vdelta_0p;
    NSInteger res;
    NSInteger SOC_low_p;
    NSInteger Tmos_OTP;
    NSInteger cbcDSG;
    float currentChg, currentDsg; //充电电流 放电电流
    float soc, soh;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topSpace.constant = IphoneX ? 54 : 20;
    self.balanceIV.alpha = 0.5;
    self.cellIV.alpha = 0.5;
    self.bmsIV.alpha = 0.5;
    self.balanceLabel.alpha = 0.5;
    self.cellLabel.alpha = 0.5;
    self.bmsLabel.alpha = 0.5;
    self.alarmRealtimeDataList = [[NSMutableArray alloc] init];
    self.cycles = 0;
    self.isCurrentPage = YES;
    
    self.tipsLabel.text = NSLocalizedString(@"*Real-time data", nil);
    self.capTitleLabel.text = NSLocalizedString(@"Capacity", nil);
    self.curTitleLabel.text = NSLocalizedString(@"Current", nil);
    self.voltTitleLabel.text = NSLocalizedString(@"Voltage", nil);
    self.balanceLabel.text = NSLocalizedString(@"Balance", nil);
    self.cellLabel.text = NSLocalizedString(@"Cell", nil);
    self.bmsLabel.text = NSLocalizedString(@"BMS", nil);
    self.bleTitleLabel.text = NSLocalizedString(@"Bluetooth", nil);
    self.moreTitleLabel.text = NSLocalizedString(@"More Info", nil);
    self.controlTitleLabel.text = NSLocalizedString(@"Control Center", nil);
    self.tipsContentLabel.text = NSLocalizedString(@"This data is real-time monitoring data.", nil);

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:kBTConnectionSucceed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectFail) name:kBTFailToConnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectFail) name:kBTDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];

    BOOL isOnline = NO;
    for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
        if ([p.identifier.UUIDString isEqualToString:self.model.uuid]) {
            isOnline = YES;
            self.peripheral = p;
            break;
        }
    }
    if (isOnline) {
        [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Connecting", @"") timer:10];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[BTManager sharedBTManager] connectPeripheral:self.peripheral];
        });
    }
    
    self.tipsLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionShowTips)];
    [self.tipsLabel addGestureRecognizer:tap];
}

- (void)actionShowTips {
    self.tipsView.hidden = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.titleLabel.text = [[BTManager sharedBTManager].diviceNameDict objectForKey:self.model.name] ?: self.model.name;
    self.isCurrentPage = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isCurrentPage = NO;
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    if ([BTManager sharedBTManager].peripheral) {
        [[BTManager sharedBTManager] disconnectRootPeripheral];
    }
}

- (void)connectFail {
    [ProgressHUD hideHUD];
    self.swBtn.selected = NO;
    [self.timer invalidate];
    self.timer = nil;
}

- (void)connectSuccess {
    [ProgressHUD hideHUD];
    self.swBtn.selected = YES;
    [self startQueruy];
}

- (void)startQueruy {
    WeakSelf
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (!weakSelf.isCurrentPage) {
            return;
        }
        switch (weakSelf.queryOrder % 4) {
            case 0:
                [weakSelf queryBMS];
                break;
            case 1:
                [weakSelf queryBatteryTemperature];
                break;
            case 2:
                [weakSelf queryBatteryOther];
                break;
            case 3:
                [weakSelf queryClock];
                break;
            case 4:
                [weakSelf queryBaseClock];
                break;
            default:
                break;
        }
        weakSelf.queryOrder ++;
    }];
}

- (IBAction)actionBalance:(id)sender {
}

- (IBAction)actionCell:(id)sender {
    DeviceCellViewController *vc = [[DeviceCellViewController alloc] initWithNibName:@"DeviceCellViewController" bundle:nil];
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)actionBMS:(id)sender {
    DeviceBMSViewController *vc = [[DeviceBMSViewController alloc] initWithNibName:@"DeviceBMSViewController" bundle:nil];
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isCurrentPage = YES;
    });
}

- (IBAction)actionSW:(id)sender {
    if (!self.peripheral) {
        return;
    }
    if ([BTManager sharedBTManager].peripheral) {
        [[BTManager sharedBTManager] disconnectRootPeripheral];
    }else {
        [ProgressHUD showActivityMessageInWindow:NSLocalizedString(@"Connecting", nil) timer:10];
        [[BTManager sharedBTManager] connectPeripheral:self.peripheral];
    }
}

- (IBAction)actionMore:(id)sender {
    DeviceMoreInfoViewController *vc = [[DeviceMoreInfoViewController alloc] initWithNibName:@"DeviceMoreInfoViewController" bundle:nil];
    vc.model = self.model;
    vc.cycles = @(self.cycles).description;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)actionDC:(id)sender {
    DeviceDCViewController *vc = [[DeviceDCViewController alloc] initWithNibName:@"DeviceDCViewController" bundle:nil];
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)actionTipsClose:(id)sender {
    self.tipsView.hidden = YES;
}

- (void)updateUI {
    self.balanceIV.alpha = self.haveBalance ? 1 : 0.5;
    self.cellIV.alpha = 1;
    self.bmsIV.alpha = 1;
    self.balanceLabel.alpha = self.haveBalance ? 1 : 0.5;
    self.cellLabel.alpha = 1;
    self.bmsLabel.alpha = 1;

    self.currentLabel.text = [NSString stringWithFormat:@"%.2fA", self.current];
    self.voltageLabel.text = [NSString stringWithFormat:@"%.2fV", self.voltage];
    self.capacityLabel.text = [NSString stringWithFormat:@"%.2fAh", self.capacity];
    self.tempCLabel.text = [NSString stringWithFormat:@"%.1f℃", self.templerature];
    self.tempFLabel.text = [NSString stringWithFormat:@"%.1f℉", self.templerature * 1.8 + 32];
    self.scoLabel.text = [NSString stringWithFormat:@"%.1f%%", soc];
    self.tempIV.image = [UIImage imageNamed:heatTag == 1 ? @"temp_icon_s" : @"temp_icon"];
    
    NSArray *arr = @[self.socView2, self.socView3, self.socView3, self.socView4, self.socView5, self.socView6, self.socView7, self.socView8, self.socView9];
    self.socView1.backgroundColor = [RGB16(0x4EC926) colorWithAlphaComponent:0.2];
    self.socView10.backgroundColor = [RGB16(0x4EC926) colorWithAlphaComponent:0.2];
    if (soc > 0) {
        self.socView1.backgroundColor = RGB16(0x4EC926);
    }
    if (soc == 100) {
        self.socView10.backgroundColor = RGB16(0x4EC926);
    }

    for (NSInteger i=0; i<arr.count; i++) {
        UIView *v = arr[i];
        v.backgroundColor = [RGB16(0x4EC926) colorWithAlphaComponent:0.2];
        if (i <= (soc / 10.0 - 1)) {
            v.backgroundColor = RGB16(0x4EC926);
        }
    }
    
    NSInteger totalMinutes = 0;
    if (self.current > 0) {
        if (currentChg) {
            totalMinutes = (self.fullCapicity - self.capacity) / self.current * 60;
        }else {
            totalMinutes = self.capacity / self.current * 60;
        }
    }
    NSInteger days = totalMinutes / (24 * 60);
    NSInteger remainingMinutes = totalMinutes % (24 * 60);
    NSInteger hoursValue = remainingMinutes / 60;
    NSInteger minutes = remainingMinutes % 60;
    NSString *str = @"";
    if (days > 0) {
        str = [str stringByAppendingFormat:@" %ldd", (long)days];
    }
    if (hoursValue > 0) {
        str = [str stringByAppendingFormat:@" %ldh", hoursValue];
    }
    if (minutes > 0) {
        str = [str stringByAppendingFormat:@" %ldm", minutes];
    }
    if (!str.length) {
        str = @"0h 0m";
    }
    self.timeLabel.text = [NSString stringWithFormat:@"%@:  %@", NSLocalizedString(@"Expect full time", nil), str];
    if (currentDsg>0) {
        self.stateLabel.text = NSLocalizedString(@"Discharging", nil);
    } else if (currentChg>0) {
        self.stateLabel.text = NSLocalizedString(@"Charging", nil);
//    }else if (cbcDSG > 0 && (self.preMOS==0) &&(self.chgMOS==0) && (self.dsgMOS==0) && (self.preRelay==0)&& (self.chgRelay==0)&&(self.dsgRelay==0)&&(self.mainRelay==0)){
//        self.stateLabel.text = NSLocalizedString(@"Short Circuit", nil);
//    } else if (CHG_0C>0||DSG_0C>0){
//        self.stateLabel.text = NSLocalizedString(@"Over Current", nil);
//    }else if (Cellchg_0T>0||Celldsg_0T>0){
//        self.stateLabel.text = NSLocalizedString(@"Over Temperature", nil);
//    }else if (Vcell_0v>0||Vbat_0V>0||soc>=100){
//        self.stateLabel.text = NSLocalizedString(@"Over Voltage", nil);
//    }else if (Vcell_UV>0||Vbat_UV>0){
//        self.stateLabel.text = NSLocalizedString(@"Under Voltage", nil);
    }else {
        self.stateLabel.text = NSLocalizedString(@"Standby", nil);
    }
}

- (void)queryBMS {
    //主机读取电池电压数据
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD0;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x26;
    bytes[6] = 0xfc;
    bytes[7] = 0xd0;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryClock {
    //主机读取时钟及保护记录
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD1;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x15;
    bytes[6] = 0xbd;
    bytes[7] = 0x39;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBatteryTemperature {
    //3.2 主控读取电池温度电流等信息
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD0;
    bytes[3] = 0x26;
    bytes[4] = 0x00;
    bytes[5] = 0x19;
    bytes[6] = 0x5d;
    bytes[7] = 0x0b;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBatteryOther {
    //主机读取电池其他信息
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0xD1;
    bytes[3] = 0x15;
    bytes[4] = 0x00;
    bytes[5] = 0x0c;
    bytes[6] = 0x6d;
    bytes[7] = 0x37;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)queryBaseClock {
    //系统基础参数读取
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0x23;
    bytes[3] = 0x1C;
    bytes[4] = 0x00;
    bytes[5] = 0x04;
    bytes[6] = 0x8E;
    bytes[7] = 0x4B;
    [[BTManager sharedBTManager] sendCommand:bytes length:8];
}

- (void)didReciveData:(NSNotification *)notification {
    NSData *reciveData = notification.object;
    Byte *dataBytes = (Byte*)reciveData.bytes;
    NSLog(@"receieve %@",reciveData);
    if (dataBytes[2]==0x2a) {
        //3.3 主控读取时钟及保护记录等信息
        //AFE1异常标志
        afe1 = dataBytes[3+0x09*2];
        //AFE2异常标志
        afe2 = dataBytes[3+0x09*2+1];
        can = dataBytes[3+0x0a*2];
        //EEP通讯异常标志
        eepCommunicate = dataBytes[3+0x0a*2+1];
        spi = dataBytes[3+0x0b*2];
        //EEP存储异常标志
        NSInteger eepStorage = dataBytes[3+0x0f*2];
        Upper = dataBytes[3+0x0b*2+1];
        Client1 = dataBytes[3+0x0c*2];
        LCD = dataBytes[3+0x0c*2+1];
        Wifi = dataBytes[3+0x0d*2];
        BLE = dataBytes[3+0x0d*2+1];
        APP = dataBytes[3+0x0e*2];
        EEPstorage = dataBytes[3+0x0f*2];
        HSE = dataBytes[3+0x0f*2+1];
        LSE = dataBytes[3+0x10*2];
        FLASH = dataBytes[3+0x10*2+1];
        BALANCE = dataBytes[3+0x11*2];
        ADC = dataBytes[3+0x11*2+1];
        HEAT = dataBytes[3+0x12*2];
        COOL = dataBytes[3+0x12*2+1];
        //CBC_CHG异常标志
         cbcCHG = dataBytes[3+0x0e*2+1];
        //CBC_DSG异常标志
        cbcDSG = dataBytes[3+0x13*2];

        if ((self.preMOS>0) | (self.chgMOS>0) | (self.dsgMOS>0) | (self.preRelay>0)| (self.chgRelay>0) | (self.dsgRelay>0) | (self.mainRelay>0)) {
            cbcDSG = 0;
            cbcDSG = 0;
        }
        NSInteger hardwareAlarm = afe1 + afe2 + eepCommunicate + eepStorage + cbcDSG + cbcCHG;
        NSInteger batteryAlarm = self.voltageSingleExceed + self.voltageSingleLower + self.voltageTotalLower + self.chargingExceed + self.disChargingExceed + self.disChargingTemperatureExceed + self.disChargingTemperatureLower + self.voltageDifferenceExceed;
        if(hardwareAlarm + batteryAlarm > 0) {
            [[PlayManager sharedManager] playAudio];
        }else {
            [[PlayManager sharedManager] stopAudio];
        }
    }
    if (dataBytes[2]==0x4c) {
        //3.1 主控读取电池电压数据
        self.voltage = (float)(dataBytes[3+0x25*2]*256+dataBytes[3+0x25*2+1]);
        self.voltage = (self.voltage * 10) / 1000.0;
    }
    if (dataBytes[2]==0x18) {
        //主机读取电池其他信息 3.4
        heatTag = dataBytes[3] & 0x01;
        NSInteger secondByte = dataBytes[4];
        //预充MOS管
        self.preMOS = (secondByte & 0x02) > 0 ? 1 : 0;
        //充电MOS管
        self.chgMOS = (secondByte & 0x04) > 0 ? 1 : 0;
        //放电MOS管
        self.dsgMOS = (secondByte & 0x08) > 0 ? 1 : 0;
        //预充继电器
        self.preRelay = (secondByte & 0x10) > 0 ? 1 : 0;
        //分口充电继电器
        self.chgRelay = (secondByte & 0x20) > 0 ? 1 : 0;
        //分口放电继电器
        self.dsgRelay = (secondByte & 0x40) > 0 ? 1 : 0;
        //同口主继电器
        self.mainRelay = (secondByte & 0x80) > 0 ? 1 : 0;
    }
    if ( (dataBytes[2]==0x32)& (reciveData.length>30)) {
        //3.2 主控读取电池温度电流等信息
        currentChg = (float) ((dataBytes[3 + 0xc * 2] * 256 + dataBytes[3 + 0xc * 2 + 1])) / 10.0f;
        currentDsg = (float) ((dataBytes[3 + 0xd * 2] * 256 + dataBytes[3 + 0xd * 2 + 1])) / 10.0f;
        
        soc = dataBytes[3 + 0x0e * 2] * 256 + dataBytes[3 + 0x0e * 2 + 1]; //SOC
        soh = dataBytes[3 + 0x0e * 2 + 2] * 256 + dataBytes[3 + 0x0e * 2 + 3]; //SOH
        self.current = currentDsg;
        if (currentChg > 0) self.current = currentChg;

        self.capacity = dataBytes[3 + 0x10 * 2] * 256 + dataBytes[3 + 0x10 * 2 + 1];
        self.capacity = self.capacity/100.0;
        self.fullCapicity = dataBytes[3+0x11*2]*256+dataBytes[3+0x11*2+1];
        self.fullCapicity = self.fullCapicity/100.0;
        
        //最高温度
        self.templerature = dataBytes[3+0x0a*2]*256 + dataBytes[3+0x0a*2+1];
        self.templerature = (self.templerature-400)/10.0;

        NSInteger serialBalance16=dataBytes[3+0x17*2]*256+dataBytes[3+0x17*2+1]; //1-16 均衡状态
        NSInteger serialBalance32=dataBytes[3+0x18*2]*256+dataBytes[3+0x18*2+1]; //17-32 均衡状态
        self.haveBalance = (serialBalance16 + serialBalance32) > 0;
        
        //三级保护信息
        self.cycles = dataBytes[3+0x13*2]*256 + dataBytes[3+0x13*2+1];
        NSInteger thirdSafeystatus = dataBytes[3+0x16*2];
        NSInteger thirdSafeystatusSecondbyte = dataBytes[3+0x16*2+1];
        //单节过压
        self.voltageSingleExceed = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;
        //单节欠压
        self.voltageSingleLower = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;
        //总压欠压
        self.voltageTotalLower = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;
        //充电过流
        self.chargingExceed = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;
        //放电过流
        self.disChargingExceed = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;
        //放电过温
        self.disChargingTemperatureExceed = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;
        //充电低温
        self.chargingTemperatureLower = (thirdSafeystatus & 0x01) > 0 ? 1 : 0;
        //放电低温
        self.disChargingTemperatureLower = (thirdSafeystatus & 0x02) > 0 ? 1 : 0;
        //压差过大
        self.voltageDifferenceExceed = (thirdSafeystatus & 0x04) > 0 ? 1 : 0;
        
        Vcell_0v = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;//单节过压
        Vcell_UV = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;//单节欠压
        Vbat_0V = (thirdSafeystatusSecondbyte & 0x04) > 0 ? 1 : 0;//总压过压
        Vbat_UV = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;//总压欠压
        CHG_0C = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;//充电过流
        DSG_0C = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;//放电过流
        Cellchg_0T = (thirdSafeystatusSecondbyte & 0x40) > 0 ? 1 : 0;//充电过温
        Celldsg_0T = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;//放电过温

        Cellchg_UT = (thirdSafeystatus & 0x01) > 0 ? 1 : 0;//充电低温
        Celldsg_UT = (thirdSafeystatus & 0x02) > 0 ? 1 : 0;//放电低温
        Vdelta_0p = (thirdSafeystatus & 0x04) > 0 ? 1 : 0;//压差过大
        res = (thirdSafeystatus & 0x08) > 0 ? 1 : 0;//预留
        SOC_low_p = (thirdSafeystatus & 0x10) > 0 ? 1 : 0;//soc过低
        Tmos_OTP = (thirdSafeystatus & 0x20) > 0 ? 1 : 0;//mos过温
    }
    [self updateUI];

    [self syncAlarmAdapter];
}

- (void)syncAlarmAdapter {
    [self.alarmRealtimeDataList removeAllObjects];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", afe1]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", afe2]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", can]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", eepCommunicate]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", spi]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Upper]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Client1]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", LCD]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Wifi]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", BLE]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", APP]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", cbcCHG]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld",EEPstorage]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", HSE]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", LSE]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", FLASH]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", ADC]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", HEAT]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", COOL]];
    //[self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", socCalib]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", res5]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", res6]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", cbcDSG]];
    
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Vcell_0v]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Vcell_UV]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Vbat_0V]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Vbat_UV]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", CHG_0C]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", DSG_0C]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Cellchg_0T]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Cellchg_UT]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Celldsg_0T]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Celldsg_UT]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Vdelta_0p]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", res]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", Tmos_OTP]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", SOC_low_p]];
    [self.alarmRealtimeDataList addObject:[NSString stringWithFormat:@"%ld", BALANCE]];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alarmdata" object:self.alarmRealtimeDataList];
}

@end
